# koroFileHeader at Yungoal acer
# Create: 2022-10-19 17:24:53
# LastEdit: 2022-10-27 17:50:07
"""事前准备好缓存内容

缓存命中问题: 用于缓存的key不同，导致测试的key和直接用网页访问的key不同。
    差别在request.build_absolute_uri()获取到的绝对路径，具体是差在SERVER_NAME和SERVER_PORT。
    可以在clinet.get请求中设置参数

ALLOWED_HOSTS问题（没问题）: 测试的默认HOST是testserver，但是上面SERVER_NAME和SERVER_PORT改掉HOST，需要允许修改后的HOST
    这里用的不是测试的Web服务，使用的还是默认的Web服务，ALLOWED_HOSTS还是默认的本地地址而非testserver，不用改。
"""
__author__ = '749B'


if __name__ == '__main__':
    # 导入路径
    from pathlib import Path
    BASE_DIR = Path(__file__).resolve().parent.parent
    import sys
    sys.path.append(BASE_DIR.__str__())
    # Django 初始化
    import django
    from django.conf import settings
    from azure_ea_insights import settings as my_settings
    settings.configure(**{ k: v for k, v in vars(my_settings).items() if k.isupper() })
    django.setup()


import time
import urllib.parse

from django.test import Client
from django.urls import reverse

from billing import models, views


class DjangoClient():

    def __init__(self) -> None:
        self.client = Client()
        sub_list = models.Subscriptions.objects.values_list('id', flat=True)
        self.sub_list = list(sub_list) + ['']
        # settings.ALLOWED_HOSTS=['*']  # 这里还是默认的而非测试用的ALLOWED_HOSTS
        self.time_result = []

    def report_time(self, start_time, key):
        """计算持续时间、打印、然后存入列表"""
        cost_time = time.time() - start_time
        self.time_result.append((cost_time, key))
        print(format(cost_time, '.2f'), '\t%s' % key)

    def report_time_top(self, top=10):
        print('耗时最长的记录:')
        self.time_result.sort(reverse=True)
        for res in self.time_result[:top]:
            print(format(res[0], '.2f'), '\t%s' % res[1])
        return self

    def get(self, viewname, data=None):
        url = reverse(viewname)
        start_time = time.time()
        response = self.client.get(url, data=data, SERVER_NAME="127.0.0.1", SERVER_PORT="8000")
        if data:
            params = urllib.parse.urlencode(data)
            key = "%s?%s" % (url, params)
            self.report_time(start_time, key)
        else:
            self.report_time(start_time, url)
        assert response.status_code == 200

    def cache_cost_monthly(self):
        viewname = 'billing:cost_monthly'
        self.get(viewname)
        for sub_id in self.sub_list:
            data = {'subid': sub_id}
            self.get(viewname, data)
        return self

    def cache_cost_table(self):
        viewname = 'billing:cost_table'
        self.get(viewname)
        return self

    def cache_cost_last30days(self):
        viewname = 'billing:cost_last30days'
        self.get(viewname)
        for sub_id in self.sub_list:
            data = {'subid': sub_id}
            self.get(viewname, data)
        return self

    def cache_cost_daily_picker(self):
        viewname = 'billing:cost_daily_picker'
        self.get(viewname)
        for sub_id in self.sub_list:
            data = {'subid': sub_id, 'start_date': '', 'end_date': ''}
            self.get(viewname, data)
        return self

    def cache_compare_monthly(self):
        viewname = 'billing:compare_monthly'
        self.get(viewname)
        return self

    def cache_cost_screen(self):
        start_time = time.time()
        views.primary.cost_subscription_month_cache()
        self.report_time(start_time, 'cache_cost_screen')
        return self

    def cache_table_cpp_count(self):
        viewname = 'billing:table_cpp_count'
        self.get(viewname)
        return self


if __name__ == '__main__':
    (
        DjangoClient()
        .cache_cost_monthly()
        .cache_cost_table()
        .cache_cost_last30days()
        .cache_cost_daily_picker()
        .cache_compare_monthly()
        .cache_cost_screen()
        .cache_table_cpp_count()
        .report_time_top()
    )
